import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import local from './localstorage'
import { Toast } from 'mint-ui'

let instance = axios.create({})
instance.interceptors.request.use(
  (config) => {
    const token = local.get('USER_TOKEN')
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.authorization = token //请求头加上token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  (response) => {
    //拦截响应，做统一处理
    if (response.data.status) {
      const status = response.data.status
      switch (status) {
        case 403:
          local.clear()
          Toast({
            message: '账号过期，需要重新登录！',
            duration: 3000
          })
          window.location.href = `${process.env.LOGIN_URL}#/login`
        case 401:
          local.clear()
          Toast({
            message: '账号过期，需要重新登录!',
            duration: 3000
          })
          window.location.href = `${process.env.LOGIN_URL}#/login`
      }
    }
    return response
  },
  //接口错误状态处理，也就是说无响应时的处理
  (error) => {
    Toast({
      message: '接口错误，请重新登录',
      duration: 3000
    })
    window.location.href = `${process.env.LOGIN_URL}#/login`
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  }
)

const request = {
  post(url, params) {
    if (!params) {
      params = {}
    }
    return instance.post(url, params, {
      transformRequest: [
        (params) => {
          let result = ''
          Object.keys(params).forEach((key) => {
            if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
              result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
            }
          })
          return result
        }
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  get(url, params) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (let key in params) {
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    return instance.get(`${url}${_params}`)
  }
}

export default request
